import Router from '@koa/router';
import { BeError, BeSuccess } from '../utils/response';
import { AddUser, GetUserList, GetUser, GetUserByName, UpdateUser } from '../services/systemUser';
import log from '../utils/log';

const router = new Router();

// 用户列表
router.get('/list', async function (ctx) {
  const { page, userName } = ctx.query;
  try {
    const data = await GetUserList(page, userName);
    ctx.body = BeSuccess(data);
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message);
  }
});

// 添加用户
router.post('/add', async function (ctx) {
  const { username, nickname, password } = ctx.request.body;
  try {
    const info = await GetUserByName(username);
    if (info) {
      throw new Error('用户名重复');
    }

    log.debug('【系统】：添加用户');
    await AddUser(null, username, nickname, password);
    ctx.body = BeSuccess('成功');
  } catch (error) {
    ctx.body = BeError(error.message);
  }
});

router.post('/del', async function (ctx) {
  const { id } = ctx.request.body;

  try {
    const info = await GetUser(id);
    if (!info) {
      throw new Error('不存在');
    }

    info.status = 0;
    const data = await UpdateUser({ status: 0 }, id);
    ctx.body = BeSuccess(data);
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message);
  }
});

export default router.routes();
